package com.sooth.system.online.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.sooth.common.core.constant.CacheConstants;
import com.sooth.common.core.domain.R;
import com.sooth.common.core.utils.StringUtils;
import com.sooth.common.log.annotation.Log;
import com.sooth.common.redis.utils.RedisUtils;
import com.sooth.common.web.core.BaseController;
import com.sooth.system.online.view.UserOnline;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 在线用户监控
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user-online")
public class SysUserOnlineController extends BaseController {

    /**
     * 获取在线用户监控列表
     *
     * @param ip       IP地址
     * @param userName 用户名
     */
    @SaCheckPermission("system:user-online:query")
    @GetMapping("/list")
    public R<List<UserOnline>> list(String ip, String userName) {
        // 获取所有未过期的 token
        List<String> keys = StpUtil.searchTokenValue("", 0, -1, false);
        List<UserOnline> userOnlineList = new ArrayList<>();
        for (String key : keys) {
            String token = StringUtils.substringAfterLast(key, ":");
            // 如果已经过期则跳过
            if (StpUtil.stpLogic.getTokenActiveTimeoutByToken(token) < -1) {
                continue;
            }
            UserOnline userOnline = RedisUtils.getCacheObject(CacheConstants.ONLINE_TOKEN_KEY + token);
            if (userOnline != null && StrUtil.isNotEmpty(ip)) {
                userOnline = StrUtil.contains(userOnline.getIp(), ip) ? userOnline : null;
            }
            if (userOnline != null && StrUtil.isNotEmpty(userName)) {
                userOnline = StrUtil.contains(userOnline.getUserName(), userName) ? userOnline : null;
            }
            if (userOnline != null) {
                userOnlineList.add(userOnline);
            }
        }
        Collections.reverse(userOnlineList);
        return R.ok(userOnlineList);
    }

    /**
     * 强退用户
     *
     * @param token token值
     */
    @SaCheckPermission("system:user-online:kick")
    @Log(title = "在线用户", message = "强退在线用户")
    @DeleteMapping("/kick")
    public R<Void> kick(@RequestParam String token) {
        try {
            StpUtil.kickoutByTokenValue(token);
        } catch (NotLoginException ignored) {
        }
        return R.ok(null);
    }
}
